package william.matrix;

/**
 * @author ZhangShenao
 * @date 2024/4/27
 * @description <a href="https://leetcode.cn/problems/rotate-image/solutions/526980/xuan-zhuan-tu-xiang-by-leetcode-solution-vu3m/">...</a>
 */
public class Leetcode48_旋转图像 {
    /**
     * 首先将矩阵以中线为轴,进行水平翻转。翻转公式(x,y) -> (N-1-x,y)
     * 然后将矩阵以主对角线为轴,进行翻转。翻转公式(x,y) -> (y,x)
     * <p>
     * 时间复杂度O(N^N) 每次翻转操作,都需要遍历矩阵的一半元素 N为矩阵阶数
     * 空间复杂度O(1)
     */
    public void rotate(int[][] matrix) {
        //边界条件校验
        if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {
            return;
        }

        int N = matrix.length;

        //首先将矩阵以中线为轴,进行水平翻转。翻转公式(x,y) -> (N-1-x,y)
        for (int x = 0; x < N / 2; x++) {
            for (int y = 0; y < N; y++) {
                int tmp = matrix[x][y];
                matrix[x][y] = matrix[N - 1 - x][y];
                matrix[N - 1 - x][y] = tmp;
            }
        }

        //然后将矩阵以主对角线为轴,进行翻转。翻转公式(x,y) -> (y,x)
        for (int x = 0; x < N; x++) {
            for (int y = 0; y < x; y++) {
                int tmp = matrix[x][y];
                matrix[x][y] = matrix[y][x];
                matrix[y][x] = tmp;
            }
        }
    }
}
